<?php

namespace app\admin\controller\zhongzhuan\feiyu;

use app\common\controller\Backend;
use think\Db;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Xiansuo extends Backend
{

    /**
     * Xiansuo模型对象
     * @var \app\admin\model\zhongzhuan\feiyu\Xiansuo
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\zhongzhuan\feiyu\Xiansuo;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("enableAssignList", $this->model->enableAssignList());
        
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    
    
    
    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }        
        $result = false;
        Db::startTrans();
        try {
            //{"gender":"未知","promotion_id":"7411837090219360297","store_pack_id":"0",
            //"req_id":"20240908113608F6C5E53C557437305F64","city_name":"宿迁",
            //"external_url":"https:\/\/www.chengzijianzhan.cc\/tetris\/page\/7320438684993552435\/",
            //"promotion_name":"自动0907新标1","remark_dict":{"您的情况（全国诚意招商）":"转行创业"},
            //"adv_id":"1786419710288009","mid_info":"{&quot;titleId&quot;:7280061892453515324,&quot;videoId&quot;:7261060641321123852}",
            //"id":"7412111518189223946","clue_convert_status":"合法转化","adv_name":"YPC-北京汉台梦酒业销售有限公司",
            //"store_id":"0","address":"321300","create_time":"1725766682","clue_source":"1","province_name":"江苏",
            //"site_name":"贵州汉台酒业","app_name":"字节-通投智选","module_id":"1787218828311556","flow_type":"4",
            //"telphone":"13732682188","site_id":"7320438684993552435","name":"姜总","clue_type":"0","location":"江苏+宿迁",
            //"module_name":"0105免费领酒水报价单+利润分析报表","cid":"0"}
            $default_params = [
                "gender"=>"未知","promotion_id"=>"7411837090219360297","store_pack_id"=>"0","req_id"=>"[EC]202409011","city_name"=>"[EC]未知",
                "external_url"=>"https:\/\/www.chengzijianzhan.cc\/tetris\/page\/7320438684993552435\/","promotion_name"=>"[EC]自动0907新标1",
                "remark_dict"=>["备注"=>$params['memo']],"adv_id"=>"1786419710288009","id"=>'E'.date("YmdHis"),"clue_convert_status"=>"合法转化","adv_name"=>"YPC-北京汉台梦酒业销售有限公司",
                "store_id"=>"0","address"=>"999999","create_time"=>time(),"clue_source"=>"1","province_name"=>"未知",
                "site_name"=>"[ec]贵州汉台酒业","app_name"=>"字节-通投智选","module_id"=>"1787218828311556","flow_type"=>"4",
                "telphone"=>$params['telphone'],"site_id"=>"7320438684993552435","name"=>$params['name'],"clue_type"=>"0","location"=>"未知",
                "module_name"=>"[ec]0105免费领酒水报价单+利润分析报表","cid"=>"0",'add_type'=>1
            ];
            $save_data = [
                'clue_id'=>$default_params['id'],//线索ID
                'advertiser_id'=>$default_params['adv_id'],//广告主ID
                'name'=>$default_params['name'],//姓名
                'telphone'=>$default_params['telphone'],//电话
                'ad_id'=> empty($default_params['ad_id']) ? '' : $default_params['ad_id'],//计划ID
                'creative_id'=>$default_params['cid'],//创意id
                'site_id'=>empty($default_params['site_id']) ? '' : $default_params['site_id'],//站点ID
                'external_url'=>$default_params['external_url'],//落地页 url
                'clue_source'=>empty($default_params['clue_source']) ? '' : $default_params['clue_source'],//组件类型
                'clue_type'=>empty($default_params['clue_type']) ? '' : $default_params['clue_type'],//组件类型
                'add_type'=>1,
                'is_enable_assign'=>$params['is_enable_assign'],
                'memo'=>'备注:' .$params['memo'] ,//备注
                'clue_create_time'=>$default_params['create_time'],//线索创建时间
                'content'=> json_encode($default_params,JSON_UNESCAPED_UNICODE),              
            ];
            
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($save_data);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            
            
            $default_params = json_decode($row['content'],true);
            $default_params['remark_dict'] = ["备注"=>$params['memo']];
            $save_data = [
                'name'=>$default_params['name'],//姓名
                'telphone'=>$default_params['telphone'],//电话
                'is_enable_assign'=>$params['is_enable_assign'],
                'memo'=>'备注:' .$params['memo'] ,//备注
                'content'=> json_encode($default_params,JSON_UNESCAPED_UNICODE),              
            ];
            
            
            $result = $row->allowField(true)->save($save_data);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    
    public function assignkehu($ids){
        
        
        $row = [];
        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');
            if ($params) {
                
                $result = false;
                Db::startTrans();
                try {
                    $today_start_time = strtotime("today");
                    $assign_id = db('ec_assign_feiyu_kehu')->where(['status'=>['<>',2]])->order('id desc')->value('id');
                   if(empty($assign_id)){
                        $this->error('分配失败');
                        exit;
                    }
                    
                   $msg = '分配成功，待推送';
                    $controller = '\app\common\controller\zhongzhuan\Autoassignfeiyu';
                    $param = [];
//                    $user_info = db('ec_user')->field('id ecid,userid')->where('id',$params['user_id'])->find();
//                    $user_info['assign_id'] = 0;
                    
                    
                    $user_id_arr = explode(',', $params['user_id']);
                    $assign_user_detail = [];
                    foreach ($user_id_arr as $value){
                        $assign_user_detail[$value]['shoudong_fenpei_people'] = 0;
                    }
                    
                    
                    $kehuidlist = explode(',', $ids);
                    $assignData = [];
                    $kehuUpdateId = [];
                    $success_int = $fail_int = 0;
                    foreach ($kehuidlist as $value){
                        $kehu_item = $this->model->get($value);
                        $kehu_item['byid'] = $kehu_item['id'];
                        $kehu_item['customerName'] = $kehu_item['name'];
                        $kehu_item['customerTelephone'] = $kehu_item['telphone'];
                        $kehu_item['startTime'] = $kehu_item['clue_create_time'];
                        
                        if(!empty($kehu_item['status']))             {
                            $fail_int = $fail_int + 1;
                            continue;
                        }               
                        
                        $result = $this->getAssingUserId($assign_user_detail);
                        $user_id = $result['user_id'];
                        $assign_user_detail = $result['list'];
                        
                        
                        $user_info = db('ec_user')->field('id ecid,userid')->where('id',$user_id)->find();
                        $user_info['assign_id'] = $assign_id;
                        $data = call_user_func_array(array($controller, 'assingSignleKehuToUser'),array($kehu_item,$user_info));
                        
                                               
                        $assign_user_detail[$user_id]['shoudong_fenpei_people']=  $assign_user_detail[$user_id]['shoudong_fenpei_people'] + 1;
                        
                        $success_int = $success_int + 1;
                        $kehuUpdateId[] = $kehu_item['id'];
                        $assignData[] = $data;
                    }
                   
                    
                    if(!empty($assignData)){
                        
                        foreach ($assign_user_detail as $k =>$v){
                            $info = db('ec_assign_feiyu_kehu_detail')->where(['assign_id'=>$assign_id,'user_id'=>$k])->find();
                            if(empty($info)){                              
                                db('ec_assign_feiyu_kehu_detail')->insertGetId([
                                    'assign_id'=>$assign_id,
                                    'user_id'=>$k,
                                    'shoudong_fenpei_people'=>$v['shoudong_fenpei_people'],
                                    'createtime'=>time()
                                ]);
                            }else{
                                $shoudong_fenpei_people = $v['shoudong_fenpei_people'] + $info['shoudong_fenpei_people'];
                                db('ec_assign_feiyu_kehu_detail')->where(['assign_id'=>$assign_id,'user_id'=>$k])->update(['shoudong_fenpei_people'=>$shoudong_fenpei_people]);
                            }
                            
                            
                        }
                        
                        
                        
                        db('ec_aiuser_to_ecuser_feiyu')->insertAll($assignData);
                        db('ec_feiyu_xiansuo')->where('id','in',$kehuUpdateId)->update([
                            'status'=>1,'type'=>1
                        ]);
                    }
                    $total = count($kehuidlist);
                    $msg = "计划分配{$total}人;成功{$success_int}人;失败{$fail_int}人(已分配)。";
                    
                    $result = true;
                    
                                     
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success($msg);
                } else {
                    $this->error('分配失败');
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
      
        $this->view->assign('row',$row);
        return $this->view->fetch();
        
    }
    
    
    public  function getAssingUserId($list){
        $end_list = [];
        $min = 999999;
        $user_id = 0;
        foreach ($list as $key=> $value){
//            if($value['success_people'] >= $value['people']) continue;
            if($value['shoudong_fenpei_people'] < $min){
                $min = $value['shoudong_fenpei_people'];
                $user_id = $key;
            }
        }
                       
        
        
        return ['user_id'=>$user_id,'list'=>$list] ;
    }


}
